package com.xnx3.banmahuishou.userApplet.controller;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xnx3.DateUtil;
import com.xnx3.banmahuishou.core.entity.Agency;
import com.xnx3.banmahuishou.core.entity.OrderEvaluationRecord;
import com.xnx3.banmahuishou.core.entity.Qishou;
import com.xnx3.banmahuishou.core.entity.ScoreChangeRecord;
import com.xnx3.banmahuishou.core.entity.Wangge;
import com.xnx3.banmahuishou.core.entity.WanggeSettime;
import com.xnx3.banmahuishou.core.entity.WeixinPublicQishouOpenid;
import com.xnx3.banmahuishou.userApplet.util.UserLocationUtil;
import com.xnx3.banmahuishou.userApplet.vo.CartVO;
import com.xnx3.banmahuishou.userApplet.vo.EvaluationStatusVO;
import com.xnx3.banmahuishou.userApplet.vo.OrderVO;
import com.xnx3.banmahuishou.userApplet.vo.WorkTimeVO;
import com.xnx3.j2ee.controller.BaseController;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.SafetyUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.wangmarket.shop.core.entity.Order;
import com.xnx3.wangmarket.shop.core.entity.OrderAddress;
import com.xnx3.wangmarket.shop.core.entity.OrderGoods;
import com.xnx3.wangmarket.shop.core.service.CartService;
import com.xnx3.weixin.WeiXinAppletUtil;
import com.xnx3.weixin.WeiXinUtil;
import com.xnx3.weixin.applet.Global;
import com.xnx3.weixin.applet.login.entity.WeixinAppletUserOpenid;


/**
 * 斑马回收用户端订单相关
 * @author 管雷鸣
 */
@Controller(value="BanmahuishouUserAppletOrderController")
@RequestMapping("/userApplet/order/")
public class OrderController extends BaseController{
	@Resource
	private SqlCacheService sqlCacheService;
	@Resource
	private SqlService sqlService;
	@Resource
	private CartService cartService;
	public static WeiXinAppletUtil weixinAppletUtil;
	/**
	 * 创建订单，生成订单
	 * @author 管雷鸣
	 * @param reserveStartTime 预约日期，预约时间段的开始时间，10位时间戳，这里存的时间戳将会格式化为具体的日期显示。（斑马回收增加）
	 * @param reserveEndTime 预约日期，预约时间段的结束时间，10位时间戳，这里存的时间戳将会格式化为具体的日期显示。（斑马回收增加）
	 * @param remark 用户备注，限制100个字符
	 * @return
	 */
	@RequestMapping(value="create.json",method = {RequestMethod.POST})
	@ResponseBody
	public OrderVO create(HttpServletRequest request,
			@RequestParam(required = true, defaultValue = "") int reserveStartTime,
			@RequestParam(required = true, defaultValue = "") int reserveEndTime,
			@RequestParam(required = true, defaultValue = "") String remark){

		OrderVO orderVO = new OrderVO();
		//获取当前用户缓存的购物车
		CartVO vo = cartService.getCurrentUserCacheCartVO();

		//判断是否有下单的商品
		if(vo.getOrderGoodsList().size() == 0) {
			orderVO.setBaseVO(BaseVO.FAILURE, "您还没有下单的商品");
			return orderVO;
		}
		if(vo.getAddress() == null) {
			orderVO.setBaseVO(BaseVO.FAILURE, "您还没有设置上门取的地址");
			return orderVO;
		}

		//创建订单
		Order order = new Order();
		order.setAddress(vo.getAddress().getAddress());
		order.setAddtime(DateUtil.timeForUnix10());
		order.setAllWeight(1); //
		order.setPhone(vo.getAddress().getPhone());
		order.setRemark(SafetyUtil.xssFilter(remark));
		order.setReserveStartTime(reserveStartTime);
		order.setReserveEndTime(reserveEndTime);
		order.setState(Order.STATE_DAIJIEDAN);
		order.setStoreid(1);
		order.setTotalMoney(vo.getAllMoney());
		order.setUserid(getUserId());
		order.setUsername(SafetyUtil.xssFilter(vo.getAddress().getUsername()));
		order.setUserHead(getUser().getHead());
		order.setSheng(vo.getAddress().getSheng());
		order.setShi(vo.getAddress().getShi());
		order.setQu(vo.getAddress().getQu());
		sqlService.save(order);

		orderVO.setOrder(order);

		//订单对应的详细地址
		OrderAddress orderAddress = new OrderAddress();
		orderAddress.setAddress(vo.getAddress().getAddress());
		orderAddress.setLatitude(vo.getAddress().getLatitude());
		orderAddress.setLongitude(vo.getAddress().getLongitude());
		orderAddress.setPhone(vo.getAddress().getPhone());
		orderAddress.setUsername(vo.getAddress().getUsername());
		orderAddress.setId(order.getId());
		sqlService.save(orderAddress);

		//保存订单下的商品
		for (int i = 0; i < vo.getOrderGoodsList().size(); i++) {
			OrderGoods orderGoods = vo.getOrderGoodsList().get(i);
			orderGoods.setOrderid(order.getId());
			orderGoods.setUserid(order.getUserid());
			sqlService.save(orderGoods);
		}

		//清空购物车
		vo.setOrderGoodsList(new ArrayList<OrderGoods>());
		cartService.setCurrentUserCacheCartVO(vo);

		// 获取出售人附近最近的骑手,是工作状态 30km以内
		String str = "SELECT *,(st_distance(point(longitude,latitude),point( " + vo.getAddress().getLongitude() + "," + vo.getAddress().getLatitude() + ")) * 111195 / 1000) juli"
				+ " FROM laji_qishou WHERE state = 1 ORDER BY juli";
		List<Map<String,Object>> qishou = sqlService.findMapBySqlQuery(str);
		if(qishou != null && qishou.size() > 0) {
			Object object = qishou.get(0).get("juli");
			if (object != null) {
				String string = String.format("%.2f",object);
				Double juli = Double.valueOf(string);
				if (juli <= 30.0) {
					order.setQishouId(Integer.valueOf(qishou.get(0).get("id").toString()));
					order.setQishouName(qishou.get(0).get("name").toString());
					order.setQishouPhone(qishou.get(0).get("phone").toString());
					order.setState(Order.STATE_DAIQUHUO);
					order.setQishouHead(qishou.get(0).get("head").toString());
					sqlService.save(order);
				}
			}
			// 设置经纬度
			Object lon = qishou.get(0).get("longitude");
			if (lon != null) {
				orderVO.setLongitude(lon.toString());
			}
			Object lat = qishou.get(0).get("latitude");
			if (lat != null) {
				orderVO.setLatitude(lat.toString());
			}

		}

		// 发送小程序订阅消息
		WeixinAppletUserOpenid appletUserOpenid = sqlService.findAloneByProperty(WeixinAppletUserOpenid.class, "userid", getUserId());

		String openid = "oYaFz5QuSjPwEvfq9zJ1AE9pc3eU";
		String templateId = "Mg3rJhtFtV4cd2PKDCwSBNOVKbXsX1Mhdh4mBrMQlIo";
		if (appletUserOpenid != null) {
			openid = appletUserOpenid.getOpenid();
		}

		Map<String, String> data = new HashMap<String, String>();
		data.put("character_string1", order.getNo());//订单号
		data.put("thing12", order.getQishouName());//服务人员姓名
		data.put("phone_number5", order.getQishouPhone());//服务人手机号
		data.put("thing8", order.getAddress());//收货地址
		data.put("time10", DateUtil.intToString(order.getReserveStartTime(), "yyyy-MM-dd HH:mm") + "~" + DateUtil.intToString(order.getReserveEndTime(), "HH:mm"));//预约时间

		weixinAppletUtil.sendSubscribeTemplateMessage(templateId, openid, data);


		// 发送公众号消息通知
		WeixinPublicQishouOpenid publicQishouOpenid = sqlService.findAloneByProperty(WeixinPublicQishouOpenid.class, "userid", order.getQishouId());
		// 公众号appid
		String appId = "wxbdb3e50bee354370";
		// 公众号appSecret
		String appSecret = "a982dbff8974eece711db294d8ca4026";
		String qishouOpenid = "onpCX5lvwSbsFxj2sIacI0THkAUs";
		String publicTemplateId = "xDqqPgahOLmg1VjnL7740bd9P-X_7A85EiXrZWRtlGY";
		if (publicQishouOpenid != null) {
			qishouOpenid = publicQishouOpenid.getOpenid();
		}
		WeiXinUtil wx = new WeiXinUtil(appId, appSecret);
		Map<String, String> dataMap = new HashMap<String, String>();
		dataMap.put("first", "您有一个新订单,请及时查看");//标题
		dataMap.put("keyword1", order.getNo());//订单号
		dataMap.put("keyword2", order.getUsername());//客户姓名
		dataMap.put("keyword3", order.getAddress());//订单地址
		dataMap.put("keyword4", DateUtil.intToString(order.getReserveStartTime(), "yyyy-MM-dd HH:mm") + "~" + DateUtil.intToString(order.getReserveEndTime(), "HH:mm"));//预约时间
		dataMap.put("keyword5", "联系方式: " + order.getPhone());//其他信息
		dataMap.put("remark", "请注意查看新任务,务必在客户预约时间内上门取货");//备注

		com.xnx3.BaseVO baseVO = wx.sendTemplateMessage(publicTemplateId, qishouOpenid, dataMap,null , null);
		System.out.println(baseVO);
		ActionLogUtil.insertUpdateDatabase(request, order.getId(), "创建订单");
		return orderVO;
	}




	/**
	 * 创建订单，生成订单(v2)
	 * @author 管雷鸣
	 * @param reserveStartTime 预约日期，预约时间段的开始时间，10位时间戳，这里存的时间戳将会格式化为具体的日期显示。（斑马回收增加）
	 * @param reserveEndTime 预约日期，预约时间段的结束时间，10位时间戳，这里存的时间戳将会格式化为具体的日期显示。（斑马回收增加）
	 * @param remark 用户备注，限制100个字符
	 * @param allWeight 总重量 默认 17500g
	 * @return
	 */
	@RequestMapping(value="createv2.json",method = {RequestMethod.POST})
	@ResponseBody
	public OrderVO createv2(HttpServletRequest request,
			@RequestParam(required = true, defaultValue = "") int reserveStartTime,
			@RequestParam(required = true, defaultValue = "") int reserveEndTime,
			@RequestParam(required = true, defaultValue = "") String remark,
			@RequestParam(required = true, defaultValue = "17500") int allWeight){

		OrderVO orderVO = new OrderVO();
		//获取当前用户缓存的购物车
		CartVO vo = cartService.getCurrentUserCacheCartVO();

		//判断是否有下单的商品
		if(vo.getOrderGoodsList().size() == 0) {
			orderVO.setBaseVO(BaseVO.FAILURE, "您还没有下单的商品");
			return orderVO;
		}
		if(vo.getAddress() == null) {
			orderVO.setBaseVO(BaseVO.FAILURE, "您还没有设置上门取的地址");
			return orderVO;
		}
		if(vo.getAddress().getUsername() == null || vo.getAddress().getUsername().trim().isEmpty()) {
			orderVO.setBaseVO(BaseVO.FAILURE, "请填写有效的联系人姓名");
			return orderVO;
		}

		//创建订单
		Order order = new Order();
		order.setAddress(vo.getAddress().getAddress()+""+vo.getAddress().getHouse());
		order.setAddtime(DateUtil.timeForUnix10());
		order.setAllWeight(allWeight); //
		order.setPhone(vo.getAddress().getPhone());
		order.setRemark(SafetyUtil.xssFilter(remark));
		order.setReserveStartTime(reserveStartTime);
		order.setReserveEndTime(reserveEndTime);
		order.setState(Order.STATE_DAIJIEDAN);
		order.setStoreid(1);
		order.setTotalMoney(vo.getAllMoney());
		order.setUserid(getUserId());
		order.setUsername(SafetyUtil.xssFilter(vo.getAddress().getUsername()));
		order.setUserHead(getUser().getHead());
		order.setSheng(vo.getAddress().getSheng());
		order.setShi(vo.getAddress().getShi());
		order.setQu(vo.getAddress().getQu());
		// 根据用户下单的地址获取代理商和网格
		// 判断是哪个代理商
		String slqString = "SELECT * FROM laji_agency WHERE state = 1 AND userid > 1";
		List<Agency> list = sqlService.findBySqlQuery(slqString, Agency.class);
		int dlsUserid = UserLocationUtil.getDlsUserid(vo.getAddress().getSheng(), vo.getAddress().getShi(), vo.getAddress().getQu(), list);
		order.setDailishangUserid(dlsUserid);
		if (dlsUserid != 0) {
			Agency agency = sqlService.findAloneByProperty(Agency.class, "userid", dlsUserid);
			if(agency != null){
				order.setDailishangUsername(agency.getName());
			}
		}
		// 判断是哪个网格
		slqString = "SELECT * FROM laji_wangge WHERE state = 1 AND dailishang_userid = " + dlsUserid;
		List<Wangge> wgList = sqlService.findBySqlQuery(slqString, Wangge.class);
		for (Wangge wangge : wgList) {
			Boolean b = UserLocationUtil.isWgLocation(vo.getAddress().getLongitude(), vo.getAddress().getLatitude(), wangge.getServiceArea());
			if (b) {
				order.setWanggeUserid(wangge.getId());
				order.setWanggeUsername(wangge.getName());
			}
		}
		//TODO 前端进行判断,后端可以不用判断,为了逻辑严谨,这里也进行判断了 
		String sqlString = "SELECT * FROM laji_wangge_settime WHERE wangge_id = " + order.getWanggeUserid();
		WanggeSettime wanggeSettime = sqlService.findAloneBySqlQuery(sqlString, WanggeSettime.class);
		if (wanggeSettime != null) {
			
			/*
			 * 先判断是不是新年放假了
			 */
			Integer newYearStartTime = wanggeSettime.getNewYearStartRestTime() == null ? 0 : wanggeSettime.getNewYearStartRestTime();
			Integer newYearEndTime = wanggeSettime.getNewYearEndRestTime() == null ? 0 : wanggeSettime.getNewYearEndRestTime();
			String tip = wanggeSettime.getNewYearTip() == null ? "春节放假回家了,年后开放" : wanggeSettime.getNewYearTip();
			if (newYearStartTime > 0 && newYearEndTime > 0) {
				// 判断预约的时间是否在假期内
				if (reserveStartTime >= newYearStartTime && reserveEndTime <= newYearEndTime) {
					orderVO.setBaseVO(BaseVO.FAILURE, tip);
					return orderVO;
				}
			}
			
			/*
			 * 判断该网格是否在营业期间
			 */
			// 取出休息日
			String restTime = wanggeSettime.getRestTime();
			String[] restTimes = restTime.split(",");
			// 预约日期
			Date date = new Date();
			date.setTime(reserveStartTime * 1000L);
			String weekName = getWeekOfDate(date);
			// 判断预约的那天是否休息日
			for (String string : restTimes) {
				if (ObjectUtils.equals(weekName, string)) {
					orderVO.setBaseVO(BaseVO.FAILURE, "今日休息,请预约其他时间");
					return orderVO; 
				}
			}
			// 取出营业时间,判断是否在其内
			// 营业开始时间
			Integer startTime = Integer.valueOf(DateUtil.intToString(wanggeSettime.getStartTime(), "HH"));
			// 营业结束时间
			Integer endTime = Integer.valueOf(DateUtil.intToString(wanggeSettime.getEndTime(), "HH"));
			// 用户预约开始时间
			Integer startTimeForUser = Integer.valueOf(DateUtil.intToString(reserveStartTime, "HH"));
			// 用户预约结束时间
			Integer endTimeForUser = Integer.valueOf(DateUtil.intToString(reserveEndTime, "HH"));
			if (startTimeForUser < startTime || startTimeForUser > endTime) {
				orderVO.setBaseVO(BaseVO.FAILURE, "超出营业时间,请选择其他预约时间");
				return orderVO; 
			}
			if (endTimeForUser < startTime || endTimeForUser > endTime) {
				orderVO.setBaseVO(BaseVO.FAILURE, "超出营业时间,请选择其他预约时间");
				return orderVO; 
			}
			
		}
		// 判断该订单是新订单还是老订单,这里不管是用户什么时间注册的, 只要是第一笔订单就为新订单, 从第二笔往后就不是新订单了
		int count = sqlService.count("shop_order", " WHERE userid=" + getUserId());
		if (count == 0) {
			// 新用户下单
			order.setIsNew(1);
		}else {
			// 老用户下单
			order.setIsNew(0);
		}
		sqlService.save(order);
		orderVO.setOrder(order);

		//订单对应的详细地址
		OrderAddress orderAddress = new OrderAddress();
		orderAddress.setAddress(vo.getAddress().getAddress());
		orderAddress.setLatitude(vo.getAddress().getLatitude());
		orderAddress.setLongitude(vo.getAddress().getLongitude());
		orderAddress.setPhone(vo.getAddress().getPhone());
		orderAddress.setUsername(vo.getAddress().getUsername());
		orderAddress.setId(order.getId());
		sqlService.save(orderAddress);

		//保存订单下的商品
		for (int i = 0; i < vo.getOrderGoodsList().size(); i++) {
			OrderGoods orderGoods = vo.getOrderGoodsList().get(i);
			orderGoods.setOrderid(order.getId());
			orderGoods.setUserid(order.getUserid());
			// 设置订单下的商品默认图片
			orderGoods.setImage("https://wangmarket1634355172.obs.cn-north-4.myhuaweicloud.com/bmhsHTML/xcximg/shibai.png");
			sqlService.save(orderGoods);
		}

		//清空购物车
		vo.setOrderGoodsList(new ArrayList<OrderGoods>());
		cartService.setCurrentUserCacheCartVO(vo);

		// 获取出售人所属网格最近的骑手
		String str = "SELECT * FROM laji_qishou WHERE state = 1 AND wangge_userid = " + order.getWanggeUserid()
		+ " ORDER BY (st_distance(point(longitude,latitude),point( " + vo.getAddress().getLongitude() + "," + vo.getAddress().getLatitude() + ")) * 111195 / 1000)";
		List<Qishou> qishouList = sqlService.findBySqlQuery(str,Qishou.class);
		if(qishouList != null && qishouList.size() > 0) {
			// 拿到最近的那个骑手信息
			Qishou qishou = qishouList.get(0);
			if (qishou != null) {
				order.setQishouId(qishou.getId());
				order.setQishouName(qishou.getName());
				order.setQishouPhone(qishou.getPhone());
				order.setState(Order.STATE_DAIQUHUO);
				order.setQishouHead(qishou.getHead());
				sqlService.save(order);
			}
			// 设置经纬度
			Double lon = qishou.getLongitude();
			if (lon != null) {
				orderVO.setLongitude(lon.toString());
			}
			Double lat = qishou.getLatitude();
			if (lat != null) {
				orderVO.setLatitude(lat.toString());
			}

		}

		// 发送小程序订阅消息
		WeixinAppletUserOpenid appletUserOpenid = sqlService.findAloneByProperty(WeixinAppletUserOpenid.class, "userid", getUserId());

		String openid = "oYaFz5QuSjPwEvfq9zJ1AE9pc3eU";
		String templateId = "Mg3rJhtFtV4cd2PKDCwSBNOVKbXsX1Mhdh4mBrMQlIo";
		if (appletUserOpenid != null) {
			openid = appletUserOpenid.getOpenid();
		}

		Map<String, String> data = new HashMap<String, String>();
		data.put("character_string1", order.getNo());//订单号
		data.put("thing12", order.getQishouName());//服务人员姓名
		data.put("phone_number5", order.getQishouPhone());//服务人手机号
		data.put("thing8", order.getAddress());//收货地址
		data.put("time10", DateUtil.intToString(order.getReserveStartTime(), "yyyy-MM-dd HH:mm") + "~" + DateUtil.intToString(order.getReserveEndTime(), "HH:mm"));//预约时间

		Global.weixinAppletUtil.sendSubscribeTemplateMessage(templateId, openid, data);


		// 发送公众号消息通知
		WeixinPublicQishouOpenid publicQishouOpenid = sqlService.findAloneByProperty(WeixinPublicQishouOpenid.class, "userid", order.getQishouId());
		// 公众号appid
		String appId = "wxbdb3e50bee354370";
		// 公众号appSecret
		String appSecret = "a982dbff8974eece711db294d8ca4026";
		String qishouOpenid = "onpCX5lvwSbsFxj2sIacI0THkAUs";
		String publicTemplateId = "xDqqPgahOLmg1VjnL7740bd9P-X_7A85EiXrZWRtlGY";
		if (publicQishouOpenid != null) {
			qishouOpenid = publicQishouOpenid.getOpenid();
		}
		WeiXinUtil wx = new WeiXinUtil(appId, appSecret);
		Map<String, String> dataMap = new HashMap<String, String>();
		dataMap.put("first", "您有一个新订单,请及时查看");//标题
		dataMap.put("keyword1", order.getNo());//订单号
		dataMap.put("keyword2", order.getUsername());//客户姓名
		dataMap.put("keyword3", order.getAddress());//订单地址
		dataMap.put("keyword4", DateUtil.intToString(order.getReserveStartTime(), "yyyy-MM-dd HH:mm") + "~" + DateUtil.intToString(order.getReserveEndTime(), "HH:mm"));//预约时间
		dataMap.put("keyword5", "联系方式: " + order.getPhone());//其他信息
		dataMap.put("remark", "请注意查看新任务,务必在客户预约时间内上门取货");//备注

		com.xnx3.BaseVO baseVO = wx.sendTemplateMessage(publicTemplateId, qishouOpenid, dataMap,null , null);
		System.out.println(baseVO);
		ActionLogUtil.insertUpdateDatabase(request, order.getId(), "创建订单");
		return orderVO;
	}




	/**
	 * 取消指定订单
	 * @param orderid 要取消的订单的id，对应 order.id
	 * @return
	 * @author 管雷鸣
	 */
	@RequestMapping(value="cancel.json",method = {RequestMethod.POST})
	@ResponseBody
	public BaseVO cancel(HttpServletRequest request,
			@RequestParam(required = true, defaultValue = "") int orderid){

		Order order = sqlService.findById(Order.class, orderid);
		if(order == null) {
			return error("订单不存在");
		}
		if(order.getState().equals(Order.STATE_CANCEL)) {
			return error("订单已取消过了");
		}

		order.setState(Order.STATE_CANCEL);
		sqlService.save(order);

		/* 
		 * 要给接单的骑手发送通知，这个订单被取消掉了，不用再去取了
		 */

		ActionLogUtil.insertUpdateDatabase(request, order.getId(), "取消订单");
		return success();
	}



	/**
	 * 根据下单地址中的省市区和经纬度获取网格的营业时间以及站点休息日期(默认8点~20点,没有休息日)
	 * @author qyw
	 */
	@RequestMapping(value="getWorkTime.json",method = {RequestMethod.POST})
	@ResponseBody
	public WorkTimeVO getWorkTime(HttpServletRequest request){

		WorkTimeVO timeVO = new WorkTimeVO();
		//获取当前用户缓存的购物车
		CartVO vo = cartService.getCurrentUserCacheCartVO();
		if(vo.getAddress() == null) {
			timeVO.setBaseVO(BaseVO.FAILURE, "您还没有设置上门取的地址");
			return timeVO;
		}
		int userId = getUserId();
		if (userId <= 0) {
			timeVO.setBaseVO(BaseVO.NOT_LOGIN, "请先登录");
			return timeVO;
		}
		// 根据下单地址中的省市区和经纬度获取网格的营业时间以及站点休息日期(默认8点~20点,没有休息日)
		// 判断是哪个代理商
		String string = "SELECT * FROM laji_agency WHERE state = 1 AND userid > 1";
		List<Agency> list = sqlService.findBySqlQuery(string, Agency.class);
		int dlsUserid = UserLocationUtil.getDlsUserid(vo.getAddress().getSheng(), vo.getAddress().getShi(), vo.getAddress().getQu(), list);
		// 没有代理商直接返回默认的
		if (dlsUserid <= 0) {
			// 默认8点~20点,没有休息日
			timeVO.setEndTime(1637582400);
			timeVO.setStartTime(1637539200);
			timeVO.setRestTime("");
			return timeVO;
		}
		// 判断是哪个网格
		string = "SELECT * FROM laji_wangge WHERE state = 1 AND dailishang_userid = " + dlsUserid;
		List<Wangge> wgList = sqlService.findBySqlQuery(string, Wangge.class);
		// 网格id
		int wanggeId = 0;
		for (Wangge wangge : wgList) {
			Boolean b = UserLocationUtil.isWgLocation(vo.getAddress().getLongitude(), vo.getAddress().getLatitude(), wangge.getServiceArea());
			if (b) {
				wanggeId = wangge.getId();
			}
		}
		// 没有网格直接返回默认的
		if (wanggeId == 0) {
			// 默认8点~20点,没有休息日
			timeVO.setEndTime(1637582400);
			timeVO.setStartTime(1637539200);
			timeVO.setRestTime("");
			return timeVO;
		}
		// 有网格 查一下看看有没有设置时间
		String sqlString = "SELECT * FROM laji_wangge_settime WHERE wangge_id = " + wanggeId;
		WanggeSettime wanggeSettime = sqlService.findAloneBySqlQuery(sqlString, WanggeSettime.class);
		if (wanggeSettime != null) {
			timeVO.setEndTime(wanggeSettime.getEndTime());
			timeVO.setStartTime(wanggeSettime.getStartTime());
			timeVO.setRestTime(wanggeSettime.getRestTime());
		}else {
			// 默认8点~20点,没有休息日
			timeVO.setEndTime(1637582400);
			timeVO.setStartTime(1637539200);
			timeVO.setRestTime("");
		}
		ActionLogUtil.insert(request, userId,"获取用户所属网格的营业时间以及站点休息日期");
		return timeVO;
	}


	
	
	/**
	 * 获取指定日期是星期几<br>
	 *
	 * @param date
	 * @return 指定日期是星期几
	 */
	public static String getWeekOfDate(Date date) {
	    String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
	    Calendar cal = Calendar.getInstance();
	    cal.setTime(date);
	    int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
	    if (w < 0)
	        w = 0;
	    return weekDays[w];
	}
	
	/**
	 * 订单评价
	 * @param orderid 订单id，对应 order.id
	 * @param serviceAttitude 服务态度评价分数, 最高5分, 例如3.5分 这里写35
	 * @param recyclingPrice 回收价格评价分数, 最高5分, 例如3.5分 这里写35
	 * @param recoveryAging 回收时效评价分数, 最高5分, 例如3.5分 这里写35
	 * @param orderEvaluation 订单评价,用户评语
	 * @return 操作结果
	 * @author zxy
	 */
	@RequestMapping(value="orderEvaluation.json",method = {RequestMethod.POST})
	@ResponseBody
	public BaseVO orderEvaluation(HttpServletRequest request,
			@RequestParam(required = true, defaultValue = "") int orderid,
			@RequestParam(required = true, defaultValue = "") int serviceAttitude,
			@RequestParam(required = true, defaultValue = "") int recyclingPrice,
			@RequestParam(required = true, defaultValue = "") int recoveryAging,
			@RequestParam(required = false, defaultValue = "") String orderEvaluation){
		int userid = getUserId();
		User user = sqlService.findById(User.class, userid);
		if (userid <= 0) {
			return error("请先登录");
		}
		Order order = sqlService.findById(Order.class, orderid);
		if(order == null) {
			return error("订单不存在");
		}
		if (userid - order.getUserid() != 0) {
			return error("该订单不属于你,无法评价");
		}
		if (!ObjectUtils.equals(order.getState(), Order.STATE_FINISH) ) {
			return error("订单还未完成,不能评价");
		}
		//新建订单评价记录
		OrderEvaluationRecord evaluationRecord = new OrderEvaluationRecord();
		evaluationRecord.setId(orderid);
		evaluationRecord.setServiceAttitude(serviceAttitude);
		evaluationRecord.setRecyclingPrice(recyclingPrice);
		evaluationRecord.setRecoveryAging(recoveryAging);
		evaluationRecord.setOrderEvaluation(SafetyUtil.xssFilter(orderEvaluation));
		int orderEvaluationScore = (serviceAttitude + recyclingPrice + recoveryAging) / 3;
		evaluationRecord.setOrderEvaluationScore(orderEvaluationScore);
		sqlService.save(evaluationRecord);
		//评价返积分
		int jiFen = 10 ;
		//当前时间十位时间戳
		Integer trueTime = DateUtil.timeForUnix10();
		//插入订单评价产生的积分变动记录
		ScoreChangeRecord scoreChangeRecord = new ScoreChangeRecord();
		scoreChangeRecord.setUserid(userid);
		scoreChangeRecord.setAddTime(trueTime);
		scoreChangeRecord.setChangePoints(jiFen);
		scoreChangeRecord.setType(ScoreChangeRecord.TYPE_PINGJIA);
		scoreChangeRecord.setRemarks(DateUtil.intToString(trueTime, "yyyy-MM-dd HH:mm:ss") 
				+ user.getNickname() + "评价订单获得了" + jiFen +"积分,相关订单id为：" + orderid);
		scoreChangeRecord.setTitle("评价订单获得积分");
		sqlService.save(scoreChangeRecord);
		//给用户积分余额加上评价订单获得的积分
		Integer currency = user.getCurrency() < 0 ? 0 : user.getCurrency();
		user.setCurrency(currency + jiFen);
		sqlService.save(user);
		order.setState(Order.STATE_EVALUATED);
		order.setEvaluationScore(orderEvaluationScore);
		//订单评语
		order.setOrderEvaluation(orderEvaluation);
		sqlService.save(order);
		//日志插入
		ActionLogUtil.insertUpdateDatabase(request, userid, "对ID为：" + orderid + "的订单评价，评价记录：" + evaluationRecord.toString());
		return success("感谢您对祖国青山绿水作出贡献!");
	}
	
	
	/**
	 * 订单评价状态信息
	 *@param orderid 订单id
	 *@author zxy 
	 */
	@RequestMapping(value="evaluationStatus.json",method = {RequestMethod.POST})
	@ResponseBody
	public EvaluationStatusVO evaluationStatus(HttpServletRequest request,
			@RequestParam(required = true, defaultValue = "") int orderid) {
		
		EvaluationStatusVO vo = new EvaluationStatusVO();
		int userid = getUserId();
		if (userid <= 0) {
			vo.setBaseVO(BaseVO.FAILURE, "请先登录");
			return vo;
		}
		Order order = sqlService.findById(Order.class, orderid);
		if (userid - order.getUserid() != 0) {
			vo.setBaseVO(BaseVO.FAILURE, "该订单不属于你,无法查看");
			return vo;
		}
		//取该订单的评价记录
		OrderEvaluationRecord orderEvaluationRecord = sqlService.findById(OrderEvaluationRecord.class, orderid);
		//如果订单评价表内没有数据 vo设置状态 0 未评价
		if (orderEvaluationRecord == null) {
			vo.setState(0);
		}else {
			vo.setState(1);
			vo.setOrderEvaluationRecord(orderEvaluationRecord);
		}
		return vo;
		
	}
	
}
